from django.shortcuts import render
from django.views.generic import TemplateView
from commodity.models import Types, CommodityInfo


# Create your views here.

def indexView(request):
    title = "首页"
    # 控制导航栏样式
    classContent = ""
    # 获取销量最高的8个商品，按照销量降序排列
    commodityInfos = CommodityInfo.objects.order_by("-sold").all()[:8]
    types = Types.objects.all()
    # 筛选儿童服饰分类下的二级分类, 展示几个商品
    c1 = [x.seconds for x in types if x.firsts == '儿童服饰']
    clothes = CommodityInfo.objects.filter(types__in=c1).order_by('-sold')[:5]
    # 奶粉辅食
    f1 = [x.seconds for x in types if x.firsts == '奶粉辅食']
    food = CommodityInfo.objects.filter(types__in=f1).order_by('-sold')[:5]
    # 儿童用品
    g1 = [x.seconds for x in types if x.firsts == '儿童用品']
    goods = CommodityInfo.objects.filter(types__in=g1).order_by('-sold')[:5]
    # 渲染
    return render(request, "index.html", locals())

# 基于类的视图，功能和上面的一致
class indexClassView(TemplateView):
    template_name = "index.html"
    template_engine = None
    # 指定响应的content-type
    content_type = None
    # 额外模板上下文的变量
    extra_context = {'title':'首页', 'classContent':''}
    # 重写获取上午文数据的方法
    def get_context_data(self, **kwargs):
        context = super(indexClassView, self).get_context_data(**kwargs)
        context['CommodityInfos'] = CommodityInfo.objects.order_by('-sold')[:8]
        types = Types.objects.all()
        # 筛选儿童服饰分类下的二级分类, 展示几个商品
        c1 = [x.seconds for x in types if x.firsts == '儿童服饰']
        context['clothes'] = CommodityInfo.objects.filter(types__in=c1).order_by('-sold')[:5]
        # 奶粉辅食
        f1 = [x.seconds for x in types if x.firsts == '奶粉辅食']
        context['food'] = CommodityInfo.objects.filter(types__in=f1).order_by('-sold')[:5]
        # 儿童用品
        g1 = [x.seconds for x in types if x.firsts == '儿童用品']
        context['goods'] = CommodityInfo.objects.filter(types__in=g1).order_by('-sold')[:5]

        return context

    def get(self, request, *args, **kwargs):
        '''
        处理http的get请求
        从kwargs获取传过来的数据
        '''
        # 获取上下文
        context = self.get_context_data(**kwargs)
        # 渲染，返回
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

def page_not_found(request, exception):
    return render(request, '404/404.html', status=404)
def page_error(request):
    return render(request, '404/404.html', status=500)

